const fs = require('fs');
const path = require('path');
const http = require('http');

// 检查命令行参数是否正确
if (process.argv.length !== 3) {
  console.error('命令行参数格式错误。正确格式为：cmd file_name');
  process.exit(1);
}

//获取图片文件名
const fileName = process.argv[2];
console.log(fileName);

// 判断当前文件名是否为空
if (!path.basename(__filename)) {
  console.log('图片文件不存在！');
}

//打印文件读取数据
let fileData = fs.readFileSync(fileName)
console.log(fileData);

//打印文件data URI数据
const type = 'image/png/jpg/bmp'
const dataUri = `data:${type};base64,${fileData}`;
console.log(dataUri);

// 创建 HTTP 服务
const server = http.createServer((req, res) => {
  if (req.url === '/') {
    // 设置响应头，状态码为200，内容类型为text/html
    res.writeHead(200, { 'Content-Type': 'text/html' });
    const htmlContent = `
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Image in Data URI</title>
      </head>
      <body>
          <h1>Image Embedded in Data URI</h1>
          <img src="${dataUri}" alt="Embedded Image">
      </body>
      </html>
    `;
    res.end(htmlContent);
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
}).listen(8080, () => {
  console.log('Server is running');
})